package com.netty.action.transport;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * socket 阴塞io
 */
public class PlainOioServer {

    public void serve(int port) throws IOException {
        final ServerSocket socket = new ServerSocket(port);  //1 绑定服务器到指定的端口
        try {
            for (;;) {
                final Socket clientSocket = socket.accept();    //2 接受一个连接,当前事件处理完成后，接收下一个事件的处理
                System.out.println("Accepted connection from " + clientSocket);

                new Thread(new Runnable() { //3创建一个新线程来处理数据
                    @Override
                    public void run() {
                        OutputStream out;
                        try {
                            out = clientSocket.getOutputStream();
                            out.write("Hi I'm Block Io Server!\r\n".getBytes(Charset.forName("UTF-8")));//4 将消息发送到连接的客户端。
                            out.flush();
                            Thread.sleep(300L);//加一个延迟，免得过快关闭连接，导致客户端收不到消息,用于EchoClient来测试
                            clientSocket.close();//5 一旦消息被写入和刷新时就 关闭连接。

                        } catch (IOException | InterruptedException e) {
                            e.printStackTrace();
                            try {
                                clientSocket.close();
                            } catch (IOException ex) {
                                // ignore on close
                            }
                        }
                    }
                }).start(); //6 启动线程
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动服务端,并且可以用EchoClient来测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        new PlainOioServer().serve(4200);
    }
}
